package com.quanfaqiang.demo1.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Properties;

@RestController
public class CaptchaController {

    private final DefaultKaptcha captchaProducer;

    public CaptchaController() {
        // 配置验证码生成器
        this.captchaProducer = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.image.width", "150");
        properties.setProperty("kaptcha.image.height", "50");
        properties.setProperty("kaptcha.textproducer.font.size", "45");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "Arial");
        captchaProducer.setConfig(new Config(properties));
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成验证码文本
        String capText = captchaProducer.createText();
        // 将验证码文本保存到session
        request.getSession().setAttribute("captcha", capText);

        // 利用验证码文本生成图像
        BufferedImage bi = captchaProducer.createImage(capText);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(bi, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();

        // 发送图像数据作为响应
        response.getOutputStream().write(imageBytes);
        response.getOutputStream().flush();
        System.out.println(capText);
    }
}
